var busArr = [];
require(['gaodeMap'], function () {
    $('#iCenter').css({
        width: $(document).width(),
        height: $(document).height()
    });
    var map = new MapGaoDe(107.49023438, 36.24427318, 2);
    var polyLine;//公交线路
    var loadCarReq;//请求车辆位置的请求
    var autoNo = -1;//定时刷新
    var stmarker;
    var endmarker;
    var stationMarkers = [];//车站Marker集合
    var showLine = true;//是否显示线路
    //实时路况图层
    var trafficLayer = new AMap.TileLayer.Traffic({
        zIndex: 10,
        autoRefresh: true,
        interval: 10000
    });
    trafficLayer.setMap(map.map);

    //线路显示隐藏切换
    $('#line-toggle').on('click', 'li', function () {
        if ($(this).hasClass('active')) {
            return;
        }
        showLine = false;
        if ($(this).text() == '显示') {
            showLine = true;
            $(this).addClass('active').next().removeClass('active');
        } else {
            $(this).addClass('active').prev().removeClass('active');
        }
        if (polyLine) {
            polyLine[showLine ? 'show' : 'hide']();
        }
    });

    //清除高德地图上面的bus
    function clearGaodeBus() {
        if (busArr.length) {
            $.each(busArr, function (index, item) {
                item.clear();
            });
            busArr.splice(0, busArr.length);
        }
    }

    //清除线路
    function clearPolyline() {
        if (polyLine) {
            polyLine.setMap(null);
            polyLine = null;
        }
    }

    //清除地图上面的标记及线路
    function clearMap() {
        clearGaodeBus();
        clearPolyline();
        if (stmarker) {
            stmarker.setMap(null);
        }
        if (endmarker) {
            endmarker.setMap(null);
        }
        if (stationMarkers.length) {
            for (var i = 0; i < stationMarkers.length; i++) {
                stationMarkers[i].setMap(null);
            }
            stationMarkers.splice(0, stationMarkers.length);
        }
    }

    //查找线路地图信息及线路车辆信息
    function loadLine(city, lineName, lineId) {
        AMap.service(["AMap.LineSearch"], function () {
            var linesearch = new AMap.LineSearch({
                pageIndex: 1,
                city: city,
                pageSize: 1,
                extensions: 'all'
            });
            linesearch.search(lineName, function (status, result) {
                if (status === 'complete' && result.info === 'OK') {
                    var lineNum = result.lineInfo.length;
                    if (lineNum) {
                        var lineArr = result.lineInfo;
                        var pathArr = lineArr[0].path;
                        var stops = lineArr[0].via_stops;
                        var startPot = stops[0].location;
                        var endPot = stops[stops.length - 1].location;
                        var stationsLen = lineArr[0].via_stops.length;
                        for (var i = 0; i < stationsLen; i++) {
                            stationMarkers.push(new AMap.Marker({
                                map: map.map,
                                position: lineArr[0].via_stops[i].location,
                                offset: new AMap.Pixel(-3, -3),
                                icon: $.getProjectName() + "/component/map/images/way_btn2.png",
                                title: lineArr[0].via_stops[i].name,
                                zIndex: 13
                            }));
                        }
                        drawbusLine(startPot, endPot, pathArr);
                    }
                } else {
                    $.messager.alert('提示', '未找到对应的线路');
                }
                loadCar(lineId);
            });
        });
    }

    //绘制路线
    function drawbusLine(startPot, endPot, BusArr) {
        //绘制起点，终点
        stmarker = new AMap.Marker({
            map: map.map,
            position: [startPot.lng, startPot.lat], //基点位置
            icon: $.getProjectName() + "/component/map/images/start_flag.png",
            zIndex: 13
        });
        endmarker = new AMap.Marker({
            map: map.map,
            position: [endPot.lng, endPot.lat], //基点位置
            icon: $.getProjectName() + "/component/map/images/end_flag.png",
            zIndex: 13
        });
        //绘制乘车的路线
        polyLine = new AMap.Polyline({
            map: map.map,
            path: BusArr,
            strokeColor: "#EA03B6",//线颜色
            strokeWeight: 5//线宽
        });
        if (!showLine) {
            polyLine.hide();
        }
        map.map.setFitView();
    }

    //添加车辆图标到高德地图
    function addCarToGaodeMap(entity) {
        var title = entity.licPltNo + '车速：' + entity.spdOfMotVhi + 'Km/h';
        var bus = new Bus(map, entity.licPltNo, entity.loLgt, entity.loLtt, entity.loDrc, title,entity.upDn);
        bus.spdOfMotVhi = entity.spdOfMotVhi;
        bus.busMarker.setTitle(title);
        bus.busNoMarker.setContent('<div style="font-weight:bold;color:red;width:70px;">' + entity.licPltNo + '</div>');
        bus.busNoMarker.setTitle(title);
        busArr.push(bus);
        bus.show();
    }

    //加载线路车辆信息
    function loadCar(lineId) {
        clearGaodeBus();
        if (loadCarReq && loadCarReq.abort) {
            loadCarReq.abort();
            loadCarReq = null;
        }
        loadCarReq = $.ajaxExt({
            url: "/operationManage/getRealTimeTrafficStatus.htm?lineId=" + lineId,
            showLoadMask: false
        }).done(function (data) {
            if ($.isArray(data)) {
                $.each(data, function (index, entity) {
                    addCarToGaodeMap(entity);
                });
            }
            loadCarReq = null;
            autoNo = setTimeout(function () {
                loadCar(lineId);
            }, 10000);
        });

    }

     //左侧树
     commonFun.leftTreeNodeClickObj['lineAnaTrafficMonitor'] = function (event, treeId, treeNode) {
         if (treeNode.type === "LINE") {
             clearMap();
             clearTimeout(autoNo);
             if(treeNode.province == '北京'||treeNode.province == '上海'||
                     treeNode.province == '天津'||treeNode.province == '重庆'){
                 loadLine(treeNode.province, treeNode.name, treeNode.id);
             }else{
                 loadLine(treeNode.city, treeNode.name, treeNode.id);
             }
         }
     };
});